<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>餐厅详情</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .reviews-list {
            list-style: none;
            padding: 0;
        }

        .review-item {
            border-bottom: 1px solid #ccc;
            padding: 10px 0;
        }

        .review-rating, .review-content, .review-author {
            font-size: 16px;
            margin-bottom: 5px;
        }

        .review-rating .rating-value, .review-content .content-value, .review-author .author-value {
            font-weight: normal;
            color: #333;
        }

        .review-rating .star {
            font-size: 20px;
            color: gold;
        }

        .review-content .content-value {
            display: inline-block;
            max-width: 80%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .review-author .author-value {
            font-style: italic;
            color: #777;
        }
    </style>
</head>
<body>
<div th:replace="~{fragments/header :: header(title='餐厅详情')}"></div>

<div class="container mt-4">
    <!-- 餐厅信息 -->
    <div class="card mb-4 shadow">
        <div class="card-body">
            <h2 class="card-title" th:text="${restaurant.name}">华丽餐厅</h2>
            <p class="text-muted" th:text="${restaurant.address}">地址：北京市朝阳区西二路28号</p>
            <p class="text-muted" th:text="${restaurant.contactPhone}">电话：010-12345678</p>
            <div class="d-flex align-items-center">
                <span class="badge bg-warning text-dark">4.5 ★</span>
                <button class="btn btn-link" th:onclick="'showReviewModal(' + ${restaurant.id} + ')'">查看评价</button>
            </div>
        </div>
    </div>

    <!-- 菜品列表 -->
    <div class="row row-cols-1 row-cols-md-3 g-4">
        <div class="col" th:each="dish : ${restaurant.dishes}">
            <div class="card h-100 dish-card" th:data-restaurant-id="${restaurant.id}">
                <img th:src="${dish.image}" class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title" th:text="${dish.name}">辣椒炒肉</h5>
                    <p class="card-text" th:text="${dish.category}">热辣</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="price-tag" th:text="${dish.price}">¥25</span>
                        <button class="btn btn-primary"
                                th:data-id="${dish.id}"
                                th:data-name="${dish.name}"
                                th:data-price="${dish.price}"
                                th:data-restaurant-id="${restaurant.id}"
                                onclick="addToCart(this)">
                            加入购物车
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 购物车总计 -->
<div class="container mt-4">
    <div class="card shadow">
        <div class="card-body">
            <h5 class="card-title">购物车总计</h5>
            <p class="card-text">当前选择商品的总金额：<span id="totalAmount">¥0.00</span></p>
            <form id="checkoutForm" action="/user/checkOut" method="GET">
                <input type="hidden" name="totalAmount" id="totalAmountInput" value="0.00">
                <input type="hidden" name="restaurantId" id="restaurantIdInput" value="">
                <button type="submit" class="btn btn-primary">去结算</button>
            </form>
        </div>
    </div>
</div>

<!-- 评价模态框 -->
<div class="modal fade" id="reviewModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">用户评价</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="reviewsList" class="reviews-list">
                    <!-- 评价列表将在这里动态生成 -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let cartItems = []; // 假设这是一个包含所有购物车项的数组
    let totalAmount = 0.00; // 假设这是一个包含总金额的变量

    // 更新总金额的函数
    function updateTotalAmount() {
        totalAmount = cartItems.reduce((sum, item) => sum + parseFloat(item.price) * item.quantity, 0);
        document.getElementById('totalAmount').innerText = `¥${totalAmount.toFixed(2)}`;
        document.getElementById('totalAmountInput').value = totalAmount.toFixed(2);
    }

    // 添加到购物车的函数
    function addToCart(button) {
        const dish = {
            id: button.getAttribute('data-id'),
            name: button.getAttribute('data-name'),
            price: parseFloat(button.getAttribute('data-price')),
            quantity: 1 // 假设每次添加一个菜品的数量为1
        };
        console.log("Adding dish:", dish); // 调试信息
        cartItems.push(dish);
        updateTotalAmount();
        Swal.fire('成功!', '已加入购物车', 'success');
    }

    // 显示评价模态框的函数
    function showReviewModal(restaurantId) {
        // 发起异步请求获取评价数据
        fetch(`/review/all?restaurantId=${restaurantId}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 清空之前的评价列表
                    const reviewsList = document.getElementById('reviewsList');
                    reviewsList.innerHTML = '';

                    // 遍历评价数据并填充到模态框中
                    data.reviews.forEach(review => {
                        const reviewItem = document.createElement('div');
                        reviewItem.className = 'review-item';

                        // 等级
                        const ratingDiv = document.createElement('div');
                        ratingDiv.className = 'review-rating';
                        ratingDiv.innerHTML = '等级：<span class="rating-value">';
                        for (let i = 1; i <= 5; i++) {
                            const star = document.createElement('span');
                            star.className = 'star';
                            star.textContent = i <= review.rating ? '★' : '☆';
                            ratingDiv.querySelector('.rating-value').appendChild(star);
                        }
                        ratingDiv.appendChild(document.createTextNode(' ')); // 添加空格

                        // 内容
                        const contentDiv = document.createElement('div');
                        contentDiv.className = 'review-content';
                        contentDiv.innerHTML = '内容：<span class="content-value">' + review.content + '</span>';

                        // 评价者
                        const authorDiv = document.createElement('div');
                        authorDiv.className = 'review-author';
                        authorDiv.innerHTML = '评价者：<span class="author-value">' + review.username + '</span>';

                        // 将静态内容和动态内容组合在一起
                        reviewItem.appendChild(ratingDiv);
                        reviewItem.appendChild(contentDiv);
                        reviewItem.appendChild(authorDiv);

                        reviewsList.appendChild(reviewItem);
                    });

                    // 显示模态框
                    new bootstrap.Modal('#reviewModal').show();
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '获取评价失败',
                        text: data.message || '无法获取评价，请稍后再试！',
                        confirmButtonText: '确定'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: '网络错误',
                    text: '无法获取评价，请检查网络连接！',
                    confirmButtonText: '确定'
                });
            });
    }

    // 更新餐厅ID
    document.querySelector('.dish-card').addEventListener('click', () => {
        const restaurantId = document.querySelector('.dish-card').getAttribute('data-restaurant-id');
        document.getElementById('restaurantIdInput').value = restaurantId;
    });
</script>
</body>
</html>